package com.yokit.c2c.service;

import com.yokit.c2c.mapper.CategoryMapper;
import com.yokit.c2c.pojo.Category;
import com.yokit.c2c.pojo.User;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author fengzeng
 * @create 2021/6/17 17:31
 */
@Service
public class CategoryService {
  @Resource
  private CategoryMapper categoryMapper;

  /**
   * 获取商品分类
   * @return
   */
  public List<Category> selectAll() {
    List<Category> categoryList = categoryMapper.selectAll();

    //最后的结果
    List<Category> rootCat = new ArrayList<>();


    //找到root分类
    for (Category category : categoryList) {
      if (category.getCatPid() == 0) {
        rootCat.add(category);
      }
    }
    //为一级菜单设置子菜单，getChild是递归调用
    for (Category category : rootCat) {
      List<Category> childList = getChild(categoryList, category.getCatId());
      category.setChildren(childList);
    }
    return rootCat;
  }

  /**
   * 递归查找子菜单
   *
   * @param categoryList 要查找的列表
   * @param catId        当前菜单的id
   * @return
   */
  private List<Category> getChild(List<Category> categoryList, Integer catId) {

    //返回的子菜单列表
    List<Category> childList = new ArrayList<>();

    // 遍历所有节点，将父菜单id与传过来的id比较
    for (Category category : categoryList) {
      if (category.getCatPid().equals(catId)) {
        childList.add(category);
      }
    }
    //把子菜单的子菜单再循环一遍
    for (Category category : childList) {
      // 递归
      category.setChildren(getChild(categoryList, category.getCatId()));
    }
    // 递归退出条件
    if (childList.size() == 0) {
      return null;
    }

    return childList;
  }

}
